<?php

// +----------------------------------------------------------------------
// | token相关的业务
// +----------------------------------------------------------------------
// | @author fancsen
// +----------------------------------------------------------------------

namespace app\api\service;

use think\Request;
use think\Cache;
use app\common\lib\exception\ApiException;
use app\common\lib\enum\ScopeEnum;

class Token
{
    /**
     * 生成token
     */
    public static function generateToken($openid='')
    {
        // 32个字符组成一组随机字符串
        $randChars = getRandChar(32);
        //用三组字符串，进行md5加密
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $salt = config('api.aeskey');
        return md5($randChars.$timestamp.$salt);   
    }   

    /**
     * 通用方法：获取当前用户token变量中指定key的值
     * @param string $key 缓存中token变量种的键
     */
    public static function getCurrentTokenVar($key)
    {
        //从header头中获取token
        $token = Request::instance()->header('token');
        //从cache中取得token的值
        $vars = Cache::get($token);
        if(!$vars){
            throw new ApiException("Token已过期或无效Token",401,10001);
        }else {
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            //返回token变量值
            if(!array_key_exists($key,$vars)){
                throw new \Exception("尝试获取的Token变量不存在");
            }else {
                return $vars[$key];
            }
        }
    }

    /**
     * 通过当前token获取当前用户的uid
     */
    public static function getCurrentUidByToken()
    {
        $uid = self::getCurrentTokenVar('uid');

        return $uid;
    }

    /**
     * 前置方法：权限控制-user&super可访问
     */
    public static function needPrimaryScope()
    {
       
        $scope =  self::getCurrentTokenVar('scope');

        if($scope){
            if($scope >= ScopeEnum::User){
                return true;
            }else {
                throw new ApiException("权限不足!", 403,10002);
            }
        }else {
            throw new ApiException("Token已过期或无效Token",401,10001);
            
        }
    }

     /**
    * 验证token
    * @http post 
    * @param string $token 用户token
    * @return bool 验证结果
    */
    public static function verifyToken($token)
    {
        //从cache中取得token的值
        $token = Cache::get($token);
        if($token){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 前置方法：权限控制-user可访问
     */
    public static function needExclusiveScope()
    {
        $scope =  self::getCurrentTokenVar('scope');

        if($scope){
            if($scope == ScopeEnum::User){
                return true;
            }else {
                throw new ApiException("权限不足!", 403,10002);
            }
        }else {
            throw new ApiException("Token已过期或无效Token",401,10001);
            
        }
    }

    /**
     * 检测传入的uid号是否和当前uid相同
     * @param int $checkedUid 传入的uid
     */
    public static function isValidOperate($checkedUid)
    {
        if(!$checkedUid){
            throw new Exception("检测UID时，必须传入一个被检查的UID");
        }

        if(self::getCurrentUidByToken() != $checkedUid){
            return false;
        }
        return true;
    }

    
}
